﻿using RuiXinCoffee.BLL;
using RuiXinCoffee.Model;
using RuiXinCoffee.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RuiXinCoffee.UI
{
    public partial class ProductDetailFrom : BaseForm
    {
        private readonly Product Product;
        private decimal originalPrice; //存储原始价格
        private decimal currentPrice; //当前调整后的价格
        
        public ProductDetailFrom(int productID, string category)
        {
            try
            {
                InitializeComponent();
                ProductService productService = new ProductService();
                Product = productService.GetProductById(productID);
                if (Product == null)
                {
                    throw new BusinessException($"找不到ID为{productID}的商品");
                }

                picProduct.Image = ImageHelper.LoadImage(Product.ImageUrl);
                picProduct.SizeMode = PictureBoxSizeMode.Zoom;

                //商品名称、价格、类别
                lblName.Text = Product.Name;
                originalPrice = Product.Price; //保存原始价格
                currentPrice = originalPrice; //初始价格设为原始价格
                lblPrice.Text = currentPrice.ToString();
                lblTotal.Text = $"￥{currentPrice.ToString()}";
                lblCategory.Text = category;
                textBox1.Text = Product.Description;
                btnPlus.Click += btnPlus_Click;
                btnMinus.Click += btnMinus_Click;
                btnCart.Click += btnCart_Click;
                btnBuy.Click += btnBuy_Click;
                SetupDynamicControls();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void SetupDynamicControls()
        {
            try
            {
                //杯型  
                groupSize = CreateOptionGroup("杯型", new[] { "中杯", "大杯", "超大杯" });
                groupSize.Location = new Point(0, 20);
                groupSize.Font = new Font("幼圆", 11);
                SetDefaultSelection(groupSize, 2); //默认选择"超大杯"  
                optionsPanel.Controls.Add(groupSize);
                
                //为杯型选项添加事件处理
                if (groupSize.Controls[0] is FlowLayoutPanel flowPanel)
                {
                    foreach (Control control in flowPanel.Controls)
                    {
                        if (control is RadioButton radioButton)
                        {
                            radioButton.CheckedChanged += CupSize_CheckedChanged;
                        }
                    }
                }

                //甜度  
                groupSweetness = CreateOptionGroup("甜度", new[] { "无糖", "少糖", "正常" });
                groupSweetness.Location = new Point(0, 70);
                groupSweetness.Font = new Font("幼圆", 11);
                SetDefaultSelection(groupSweetness, 2); //默认选择"正常"  
                optionsPanel.Controls.Add(groupSweetness);

                //冰度  
                groupIce = CreateOptionGroup("冰度", new[] { "去冰", "少冰", "正常" });
                groupIce.Location = new Point(0, 120);
                groupIce.Font = new Font("幼圆", 11);
                SetDefaultSelection(groupIce, 2); //默认选择"正常"  
                optionsPanel.Controls.Add(groupIce);
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("创建选项组失败", ex));
            }
        }

        private GroupBox CreateOptionGroup(string title, string[] options)
        {
            try
            {
                GroupBox group = new GroupBox { Text = title, Width = 1000, Height = 50 };
                group.Font = new Font("幼圆", 11); //设置GroupBox标题字体为幼圆
                
                FlowLayoutPanel flow = new FlowLayoutPanel
                {
                    FlowDirection = FlowDirection.LeftToRight,
                    WrapContents = false,
                    Width = optionsPanel.Width,
                    AutoSize = true,
                    Padding = new Padding(25,0,25,0)
                };
                foreach (string opt in options)
                {
                    flow.Controls.Add(new RadioButton
                    {
                        Text = opt,
                        AutoSize = true,
                        Font = new Font("幼圆", 10),
                        Margin = new Padding(30, 0, 30, 0) 
                    });
                }
                group.Controls.Add(flow);
                return group;
            }
            catch (Exception ex)
            {
                throw new BusinessException($"创建{title}选项组失败", ex);
            }
        }

        private void SetDefaultSelection(GroupBox group, int index)
        {
            try
            {
                if (group.Controls[0] is FlowLayoutPanel flow)
                {
                    if (index >= 0 && index < flow.Controls.Count)
                    {
                        //设置默认选择
                        var radio = flow.Controls[index] as RadioButton;
                        if (radio != null)
                        {
                            radio.Checked = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("设置默认选项失败", ex));
            }
        }

        private int? GetSelectedIndex(GroupBox group)
        {
            try
            {
                if (group?.Controls.Count == 0) return null;

                FlowLayoutPanel flowPanel = group.Controls[0] as FlowLayoutPanel;

                for (int i = 0; i < flowPanel.Controls.Count; i++)
                {
                    if (flowPanel.Controls[i] is RadioButton radio && radio.Checked)
                    {
                        return i;
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                throw new BusinessException("获取选中选项失败", ex);
            }
        }

        //杯型选择变更事件
        private void CupSize_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (sender is RadioButton radioButton && radioButton.Checked)
                {
                    //根据杯型调整价格
                    switch (radioButton.Text)
                    {
                        case "中杯":
                            currentPrice = originalPrice - 5m; //中杯比原价减5元
                            break;
                        case "大杯":
                            currentPrice = originalPrice - 2m; //大杯比原价减2元
                            break;
                        case "超大杯":
                            currentPrice = originalPrice; //超大杯维持原价
                            break;
                    }
                    
                    //更新价格显示
                    lblPrice.Text = currentPrice.ToString();
                    UpdateTotalPrice();
                }
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("调整杯型价格失败", ex));
            }
        }

        //添加到购物车
        private void GetSelectedIndices()
        {
            try
            {
                int? sizeIndex = GetSelectedIndex(groupSize);        //杯型
                int? sweetnessIndex = GetSelectedIndex(groupSweetness); //甜度
                int? iceIndex = GetSelectedIndex(groupIce);           //冰度

                //检查是否所有选项都已选择
                if (!sizeIndex.HasValue || !sweetnessIndex.HasValue || !iceIndex.HasValue)
                {
                    throw new UserOperationException("请完成所有选择");
                }

                string sweet = "正常", ice = "正常";
                switch (sweetnessIndex.Value)
                {
                    case 0: sweet = "无糖"; break;
                    case 1: sweet = "少糖"; break;
                    case 2: sweet = "正常"; break;
                }
                switch (iceIndex.Value)
                {
                    case 0: ice = "无冰"; break;
                    case 1: ice = "少冰"; break;
                    case 2: ice = "正常"; break;
                }

                OrderInfo orderInfo = new OrderInfo();
                orderInfo.ProductId = Product.Id;
                orderInfo.ProductName = Product.Name;
                orderInfo.ProductImageUrl = Product.ImageUrl;
                orderInfo.CupType = sizeIndex.Value;
                orderInfo.SugarLevel = sweet;
                orderInfo.IceLevel = ice;
                orderInfo.Quantity = int.Parse(lblCount.Text);
                orderInfo.TotalPrice = decimal.Parse(lblTotal.Text.Replace("￥", ""));
                orderInfo.Price = currentPrice; //使用当前杯型对应的价格
                orderInfo.OrderTime = DateTime.Now;
                orderInfo.OrderStatus = 0;
                ShoppingCartService.Instance.AddToCart(orderInfo);
                OrderService orderService = new OrderService();
                orderService.CreateOrder(orderInfo);
            }
            catch (UserOperationException ex)
            {
                HandleException(ex);
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("添加到购物车失败", ex));
            }
        }

        private void btnPlus_Click(object? sender, EventArgs e)
        {
            try
            {
                int count = int.Parse(lblCount.Text) + 1;
                lblCount.Text = count.ToString();
                UpdateTotalPrice();
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("增加数量失败", ex));
            }
        }

        private void btnMinus_Click(object? sender, EventArgs e)
        {
            try
            {
                int count = Math.Max(1, int.Parse(lblCount.Text) - 1);
                lblCount.Text = count.ToString();
                UpdateTotalPrice();
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("减少数量失败", ex));
            }
        }

        //更新总价
        private void UpdateTotalPrice()
        {
            try
            {
                int quantity = int.Parse(lblCount.Text);
                lblTotal.Text = $"￥{currentPrice * quantity:0.00}";
            }
            catch (Exception ex)
            {
                HandleException(new BusinessException("更新价格失败", ex));
            }
        }

        //加入购物车
        private void btnCart_Click(object sender, EventArgs e)
        {
            try
            {
                GetSelectedIndices();
                this.Close();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void ProductDetailFrom_Load(object sender, EventArgs e)
        {
        }

        private void label1_Click(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
        }

        private void lblTotal_Click(object sender, EventArgs e)
        {
        }

        //立即购买
        private void btnBuy_Click(object sender, EventArgs e)
        {
            try
            {
                GetSelectedIndices();
                CartForm cartForm = new CartForm();
                cartForm.ShowWithBinding(this.Owner ?? this);
                this.Close();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
    }
}
